#include "INC.h"

sys_t sys_state = {0};
void sys_init(void)
{
	// 全局定时器
	NVIC_EnableIRQ(TIMER_SYS_INST_INT_IRQN);
	DL_Timer_startCounter(TIMER_SYS_INST);
	sys_state.update_flag = false;
	sys_state.state = IDLE;
}
void set_sys_update_flag(bool flag)
{
	sys_state.update_flag = flag;
	DL_Timer_startCounter(TIMER_SYS_INST);
}
bool get_sys_update_flag(void)
{
	return sys_state.update_flag;
}
uint8_t get_sys_running_state(void)
{
	return sys_state.state;
}
// 切换系统运行状态
void switch_sys_running_state(uint8_t key)
{
	if (key)
	{
		sys_state.state = (sys_state.state == IDLE) ? RUNNING : IDLE;
	}
}
void set_sys_running_state(uint8_t state)
{
	sys_state.state = state;
}
// 设置和获取小车转弯次数
void set_sys_target_conner(uint8_t conner)
{
	sys_state.target_conner = conner;
}
uint8_t get_sys_target_conner(void)
{
	return sys_state.target_conner;
}
void set_sys_current_conner(uint8_t conner)
{
	sys_state.current_conner = conner;
}
uint8_t get_sys_current_conner(void)
{
	return sys_state.current_conner;
}

// 小车系统定时器中断处理函数
void TIMER_SYS_INST_IRQHandler(void)
{
	switch (DL_TimerG_getPendingInterrupt(TIMER_SYS_INST))
	{
	case DL_TIMER_IIDX_ZERO:
		// 处理编码器
		sys_state.update_flag = true;
		// 清除中断标志
		// DL_TimerG_clearInterruptStatus(TIMER_SYS_INST, DL_TIMER_IIDX_ZERO);
		break;
	default:
		break;
	}
}
// 系统滴答定时器中断处理函数
void SysTick_Handler(void)
{
	tick_ms++;
}

// 编码器中断处理函数
void GROUP1_IRQHandler(void)
{
	uint32_t st = DL_GPIO_getEnabledInterruptStatus(GPIO_ENCODER_PORT,
													GPIO_ENCODER_PIN_R_0_PIN | GPIO_ENCODER_PIN_R_1_PIN |
														GPIO_ENCODER_PIN_L_0_PIN | GPIO_ENCODER_PIN_L_1_PIN |
														GPIO_KEYS_PIN_KEY_0_PIN | GPIO_KEYS_PIN_KEY_1_PIN);

	// 拍快照，避免多次读引脚时电平变化
	uint8_t right_0 = !DL_GPIO_readPins(GPIO_ENCODER_PORT, GPIO_ENCODER_PIN_R_0_PIN);
	uint8_t right_1 = !DL_GPIO_readPins(GPIO_ENCODER_PORT, GPIO_ENCODER_PIN_R_1_PIN);
	uint8_t left_0 = !DL_GPIO_readPins(GPIO_ENCODER_PORT, GPIO_ENCODER_PIN_L_0_PIN);
	uint8_t left_1 = !DL_GPIO_readPins(GPIO_ENCODER_PORT, GPIO_ENCODER_PIN_L_1_PIN);

	if (st & GPIO_ENCODER_PIN_R_0_PIN)
	{

		motor_encoder.temp_count2 += (right_1 ? -1 : +1);
	}
	else if (st & GPIO_ENCODER_PIN_R_1_PIN)
	{

		motor_encoder.temp_count2 += (right_0 ? +1 : -1);
	}
	if (st & GPIO_ENCODER_PIN_L_0_PIN)
	{

		motor_encoder.temp_count += (left_1 ? +1 : -1);
	}
	else if (st & GPIO_ENCODER_PIN_L_1_PIN)
	{

		motor_encoder.temp_count += (left_0 ? -1 : +1);
	}
	if (st & GPIO_KEYS_PIN_KEY_0_PIN)
	{
		// 按键0中断
		key_data.key0 = 1;
	}

	if (st & GPIO_KEYS_PIN_KEY_1_PIN)
	{
		// 按键1中断
		key_data.key1 = 1;
	}

	DL_GPIO_clearInterruptStatus(GPIO_ENCODER_PORT, st);
}
